<!-- subpkg_consult/room/index.vue -->
<script lang="ts" setup>
  import { orderDetailApi, uploadImageApi } from '@/api/consultPAI'
  import { useUserStore } from '@/stores/user'
  import type { OrderDetail } from '@/type/consult'
  import { onLoad } from '@dcloudio/uni-app'
  import { io, type Socket } from 'socket.io-client'
  import { nextTick, ref } from 'vue'
  import roomStatus from './components/room-status.vue'
  import PatientInfo from './components/patient-info.vue'
  import NotifyInfo from './components/notify-info.vue'
  import MessageInfo from './components/message-info.vue'
  import PrescriptionInfo from './components/prescription-info.vue'
  import RateInfo from './components/rate-info.vue'

  import type { Datum, MsgItem } from '@/type/room'

  const props = defineProps<{
    orderId: string
    payResult: string
  }>()

  let socket: Socket
  const store = useUserStore()
  const messageList = ref<MsgItem[]>([])
  const sp = ref('')
  // 5. 发送文字消息
  const textMessage = ref('')
  onLoad(() => {
    // 1. 处理支付失败
    if (props.payResult === 'false') {
      uni.switchTab({
        url: '/pages/mine/mine',
      })
      return
    }

    // 2. 建立连接
    socket = io('https://consult-api.itheima.net', {
      auth: { token: 'Bearer ' + store.user?.token },
      query: { orderId: props.orderId },
      transports: ['websocket', 'polling'],
      timeout: 5000,
    })

    socket.on('connect', () => {
      // 建立连接成功
      console.log('连接建立成功')
    })

    socket.on('error', (event) => {
      // 错误异常消息
      console.log('出现错误')
    })

    socket.on('disconnect', () => {
      // 已经断开连接
      console.log('断开连接')
    })

    socket.on('statusChange', () => {
      getOrderDetail()
    })
    socket.on('chatMsgList', (msg) => {
      console.log(msg)
      msg.data.forEach((item: Datum) => {
        messageList.value.push(
          {
            msgType: 31,
            msg: { content: item.createTime },
            id: item.createTime,
          },
          ...item.items!
        )
        nextTick(() => {
          // 滚动到底部
          sp.value = '_' + messageList.value[messageList.value.length - 1].id
          console.log(sp.value)
        })
      })
    })

    socket.on('receiveChatMsg', (message: MsgItem) => {
      // 修改消息为已读
      socket?.emit('updateMsgStatus', message.id)
      // 接收到的消息追加到消息列表中
      messageList.value.push(message)
      nextTick(() => {
        // 滚动到底部
        sp.value = '_' + messageList.value[messageList.value.length - 1].id
        console.log(sp.value)
      })
    })
  })

  // 发送文字消息
  const onInputConfirm = () => {
    // 发送消息
    socket?.emit('sendChatMsg', {
      // 当前登录用户的ID
      from: store.user?.id,
      to: orderDetail.value?.docInfo?.id,
      msgType: 1,
      msg: {
        content: textMessage.value,
      },
    })

    textMessage.value = ''
  }

  // 6. 发送图片消息
  const onImageButtonClick = async () => {
    // 是否在问诊状态中...
    if (orderDetail.value.status !== 3) {
      return uni.showToast({ title: '医生当前不在线!' })
    }
    const res = await uni.chooseImage()
    // console.log(res.tempFilePaths)
    const fp = res.tempFilePaths[0]
    const picture = await uploadImageApi(fp)
    socket.emit('sendChatMsg', {
      from: store.user?.id,
      to: orderDetail.value?.docInfo?.id,
      msgType: 4,
      msg: { picture },
    })
  }

  // 问诊订单详情
  const orderDetail = ref({} as OrderDetail)
  const getOrderDetail = async () => {
    const data = await orderDetailApi(props.orderId)
    orderDetail.value = data
  }
  onLoad(() => {
    getOrderDetail()
  })
</script>

<template>
  <view class="room-page">
    <room-status
      v-if="orderDetail?.id"
      :status-value="orderDetail.statusValue"
      :countdown="orderDetail.countdown"
      :status="orderDetail.status"
    />
    <scroll-view
      refresher-enabled
      refresher-background="#f2f2f2"
      scroll-y
      style="flex: 1; overflow: hidden"
      :scroll-into-view="sp"
    >
      <view
        class="message-container"
        v-for="item in messageList"
        :key="item.id"
        :id="'_' + item.id"
      >
        <!-- 此处将来填充更多代码... -->
        <!-- <template> -->
        <patient-info :msgItem="item" v-if="item.msgType === 21" />
        <!-- 消息通知 -->
        <notify-info v-if="item?.msgType && item?.msgType >= 31" :type="item?.msgType">
          {{ item?.msg?.content }}
        </notify-info>
        <!-- 文字消息 -->
        <message-info v-if="item.msgType && item?.msgType <= 4" :info="item" :type="item.msgType" />
        <!-- 电子处方 -->
        <PrescriptionInfo v-if="item.msgType === 22" :info="item.msg?.prescription!" />
        <!-- 医生评价 -->
        <rate-info
          :order-id="orderId"
          :doc-id="orderDetail.docInfo.id"
          :successScore="item.msg?.evaluateDoc?.score"
          v-if="item.msgType === 23 || item.msgType === 24"
        ></rate-info>
        <!-- </template> -->
      </view>
    </scroll-view>

    <!-- 发送消息 -->
    <view class="message-bar">
      <template v-if="true">
        <uni-easyinput
          v-model="textMessage"
          @confirm="onInputConfirm"
          :disabled="orderDetail.status !== 3"
          :clearable="false"
          :input-border="false"
          placeholder-style="font-size: 32rpx; color: #c3c3c5;"
          placeholder="问医生"
        />
        <view class="image-button" @click="onImageButtonClick">
          <uni-icons size="40" color="#979797" type="image"></uni-icons>
        </view>
      </template>
      <button v-else class="uni-button">咨询其它医生</button>
    </view>
  </view>
</template>

<style lang="scss">
  @import './room.scss';
</style>
